<template>
  <div class="layout-container contracting-party">
    <div class="header">
      <title-view title="配置签约主体" />
      <el-button @click="handelBack">返回上一页</el-button>
    </div>
    <div class="app-container column-layout">
      <!-- 过滤 start -->
      <div class="app-container filter-box">
        <div class="filter-box__left">
          <div class="filter-item">
            <span class="filter-item-label">主体名称</span>
            <el-input placeholder="请输入" v-model="tableParams.name" clearable />
          </div>
          <div class="filter-item">
            <span class="filter-item-label" style="text-align: right">状态</span>
            <el-select placeholder="请选择" v-model="tableParams.status">
              <el-option label="启用" :value="true"></el-option>
              <el-option label="停用" :value="false"></el-option>
            </el-select>
          </div>
        </div>
        <div class="filter-box__right">
          <el-button type="primary" icon="Search" @click="handleQueryTemplate">查询</el-button>
          <el-button type="primary" plain icon="RefreshRight" @click="handelResetFilter">重置</el-button>
        </div>
      </div>
      <!--  过滤 end  -->

      <!-- 操作按钮 start  -->
      <div class="contracting-buttons">
        <el-button type="primary" @click="handelAdd">新建</el-button>
      </div>
      <!--  操作按钮 end  -->

      <!--  模板列表 start  -->
      <el-table
        v-loading="isLoadingList"
        :data="tableData"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{ background: '#F2F6FC !important', color: '#909399', 'font-weight': 400, 'font-size': '14px' }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="enterpriseName" label="主体名称" width="250" show-overflow-tooltip />
        <el-table-column prop="socialCode" label="统一社会信用代码" show-overflow-tooltip />
        <el-table-column label="印章">
          <template #default="{ row }">
            <el-image v-if="row.signet" class="seal-image" :src="row.signet"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-tag class="ml-2" type="warning" v-if="row.authStatus === 0">{{ row.authStatusName }}</el-tag>
            <el-tag class="ml-2" type="success" v-if="row.authStatus === 1">{{ row.authStatusName }}</el-tag>
            <el-tag class="ml-2" type="info"  v-if="row.authStatus === 2">{{ row.authStatusName }} </el-tag>
            <el-tag class="ml-2" type="warning" v-if="row.authStatus === 3">{{ row.authStatusName }}</el-tag>
            <el-tag class="ml-2" type="success" v-if="row.authStatus === 4">{{ row.authStatusName }}</el-tag>
            <el-tag class="ml-2" type="info" v-if="row.authStatus === 5">{{ row.authStatusName }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="禁用/启用" align="center" width="100">
          <template #default="{ row }">
            <el-switch v-model="row.status" :loading="row.isLoadingStatus" @change="changeSignStatus(row)" />
          </template>
        </el-table-column>

        <el-table-column prop="authExpireTime" label="认证失效时间" width="180" />
        <el-table-column prop="sealExpireTime" label="授权失效时间" width="180" />
        <el-table-column prop="createTime" label="添加时间" width="180" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <el-button style="color: #409eff" type="primary" link @click="handelEdit(row)">编辑</el-button>
            <el-button
              v-if="row.authStatus === 0 || row.authStatus === 2"
              style="color: #409eff"
              type="primary"
              link
              @click="handelCertification(row)"
              >认证
            </el-button>
            <el-button
              v-if="row.authStatus === 1 || row.authStatus === 3 || row.authStatus === 5"
              style="color: #409eff"
              type="primary"
              link
              @click="handelAuthorization(row)"
              >授权
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <custom-pagination
        :total="listTotal"
        v-model:limit="tableParams.size"
        v-model:page="tableParams.current"
        layout="total, slot, prev, pager, next, jumper"
        @pagination="handelPage"
      >
      </custom-pagination>
      <!--  模板列表 end -->
    </div>

    <!--  新建 start  -->
    <div class="add-contracting-party">
      <el-drawer v-model="isOpenDrawer" :size="514" destroy-on-close @close="handelDrawerCancel">
        <template #header>
          <title-view :title="drawerTitle" />
        </template>
        <el-form
          v-if="isOpenDrawer"
          v-loading="isLoadingDrawer"
          ref="ruleDialogFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="100px"
          label-position="top"
          status-icon
        >
          <el-form-item label="企业名称" prop="enterpriseName">
            <el-input v-model.trim="addForm.enterpriseName" clearable placeholder="请输入" :disabled="addForm.authStatus > 0" />
          </el-form-item>
          <el-form-item label="统一社会信用代码" prop="socialCode">
            <el-input v-model="addForm.socialCode" clearable placeholder="请输入" :disabled="addForm.authStatus > 0" />
          </el-form-item>
          <el-form-item label="法人代表姓名">
            <el-input v-model="addForm.legalBehalf" clearable placeholder="请输入" :disabled="addForm.authStatus > 0" />
          </el-form-item>
          <el-form-item label="法人代表身份证号">
            <el-input v-model="addForm.legalBehalfCode" clearable placeholder="请输入" :disabled="addForm.authStatus > 0" />
          </el-form-item>
          <el-form-item label="有效通信地址">
            <el-input v-model="addForm.address" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="addForm.mobile" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="合同管理员姓名">
            <el-input v-model="addForm.legalBehalf" placeholder="请输入" clearable disabled />
            <text>合同管理员默认为法人，可在合同平台进行合同相关认证、管理</text>
          </el-form-item>
          <el-form-item label="印章" v-if="drawerTitle !== '新建签约主体' && addForm.authStatus !== 0">
            <div style="width: 100%">
              <el-image style="width: 85px; height: 85px" :src="addForm.signet"></el-image>
            </div>
            <div>该印章为电子签主体认证自动生成，如需编辑请联系管理员</div>
          </el-form-item>
          <el-form-item label="合同logo" prop="area">
            <image-video-upload
              :fileList="logoImageList"
              accept=".png"
              tip="注：建议使用PNG格式，单张大小不超过5MB，只支持1张"
              :max-size="5"
              :max-length="1"
              @upload-success="uploadLogoImageList"
              @upload-remove="uploadLogoImageListRemove"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="drawer-footer">
            <el-button style="background-color: #f2f3f5" @click="handelDrawerCancel">取消</el-button>
            <el-button type="primary" @click="handelDrawerConfirm" :loading="isLoadingDrawer">保存</el-button>
          </div>
        </template>
      </el-drawer>
    </div>
    <!--  新建 end  -->
    <div class="certification">
      <el-dialog v-model="dialogVisible" width="30%" center>
        <div class="certification-content">
          <div>
            {{ isType === 1 ? "机构&管理员认证" : "印章授权" }}：<a :href="authUrl" target="_blank">{{ authUrl }}</a>
          </div>
          <div class="tips">请将该链接复制给相关负责人</div>
          <!--          <div v-if="isType === 1">操作视频: <a href="https://e.xst/cccc" target="_blank">https://e.xst/cccc</a></div>-->
          <!--          <div v-else>操作视频: <a href="https://e.xst/cccc" target="_blank">https://e.xst/cccc</a></div>-->
        </div>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确认</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, nextTick, ref } from "vue";
import { useRouter } from "vue-router";
import _ from "lodash";
import { tableRowClassName, generateId } from "@/utils/util.js";
import { initAddForm } from "./config.js";
import formVerification from "@/utils/formVerification";
import { signPageList, addSign, editSign, setSignStatus, signDetail, authentication, sealAuth } from "@/apis/contractingParty";

const { proxy } = getCurrentInstance();
const router = useRouter();
const dialogVisible = ref(false);
const isType = ref(1);
const authUrl = ref("");

/**
 * 签约主体列表
 */
const isLoadingList = ref(false);
const listTotal = ref(0);
const tableParams = ref({
  current: 1,
  size: 10,
  name: "",
  status: true
});
// 认证
const handelCertification = async row => {
  const { code, data } = await authentication({ socialCode: row.socialCode });
  if (data.authUrl) {
    isType.value = 1;
    authUrl.value = data.authUrl;
    dialogVisible.value = true;
  }
  getSignPageList();
};

// 授权
const handelAuthorization = async row => {
  const { code, data } = await sealAuth({ socialCode: row.socialCode });
  if (data.authUrl) {
    isType.value = 2;
    authUrl.value = data.authUrl;
    dialogVisible.value = true;
  }
  getSignPageList();
};

const tableData = ref([]);
const getSignPageList = async () => {
  try {
    isLoadingList.value = true;
    const { data } = await signPageList(tableParams.value);
    tableData.value = data.list ?? [];
    listTotal.value = data.total ?? 0;
    isLoadingList.value = false;
  } catch (err) {
    isLoadingList.value = false;
  }
};
const handelPage = () => {
  tableData.value = [];
  getSignPageList();
};
const handleQueryTemplate = _.debounce(getSignPageList, 500);
const handelResetFilter = () => {
  tableParams.value = {
    current: 1,
    size: 10,
    name: "",
    status: true
  };
  getSignPageList();
};

const handelBack = () => {
  router.replace({
    path: "/template-list"
  });
};

/**
 * 设置签约主体状态
 */
const changeSignStatus = async row => {
  try {
    row.isLoadingStatus = true;
    await setSignStatus(row.signId, row.status);
    proxy.$modal.msgSuccess("操作成功");
    row.isLoadingStatus = false;
  } catch (err) {
    row.status = !row.status;
    row.isLoadingStatus = false;
  }
};

/**
 * 新建、编辑签约主体
 */
const isOpenDrawer = ref(false);
const isLoadingDrawer = ref(false);
const drawerTitle = ref("");
const isEdit = ref(false);
const addFormRules = {
  enterpriseName: [{ required: true, message: "请输入企业名称", trigger: "blur" }],
  socialCode: [
    { required: true, message: "请输入统一社会信用代码", trigger: "blur" },
    { validator: formVerification.USCCode, trigger: "blur" }
  ]
};
const addForm = ref({ ...initAddForm });
const handelAdd = () => {
  isOpenDrawer.value = true;
  isEdit.value = false;
  drawerTitle.value = "新建签约主体";
};
const handelEdit = async row => {
  isOpenDrawer.value = true;
  isEdit.value = true;
  drawerTitle.value = "编辑签约主体";
  try {
    isLoadingDrawer.value = true;
    const { data } = await signDetail(row.signId);
    addForm.value = { ...data };
    data.logo && logoImageList.value.push({ fileId: generateId(), fileUrl: data.logo });
    data.signet && sealImageList.value.push({ fileId: generateId(), fileUrl: data.signet });
    isLoadingDrawer.value = false;
  } catch (err) {
    isLoadingDrawer.value = false;
  }
};
// 印章图片/logo图片
const sealImageList = ref([]);
const logoImageList = ref([]);
const uploadSealImageList = data => {
  sealImageList.value = [{ ...data }];
};
const uploadSealImageListRemove = index => {
  sealImageList.value.splice(index, 1);
};
const uploadLogoImageList = data => {
  logoImageList.value = [{ ...data }];
};
const uploadLogoImageListRemove = index => {
  logoImageList.value.splice(index, 1);
};
// 提交
const handelDrawerCancel = async () => {
  await nextTick();
  await proxy.$refs.ruleDialogFormRef.resetFields();
  addForm.value = { ...initAddForm };
  sealImageList.value = [];
  logoImageList.value = [];
  isOpenDrawer.value = false;
};
const handelDrawerConfirm = async () => {
  await nextTick();
  proxy.$refs.ruleDialogFormRef.validate(async val => {
    if (!val) return proxy.$modal.msgError("请完善信息");
    try {
      isLoadingDrawer.value = true;
      const postData = {
        ...addForm.value,
        logo: logoImageList.value[0]?.fileUrl ?? "",
        signet: sealImageList.value[0]?.fileUrl ?? ""
      };
      const requestApi = isEdit.value ? editSign : addSign;
      await requestApi(postData, isEdit.value ? addForm.value.signId : "");
      proxy.$modal.msgSuccess("操作成功");
      isLoadingDrawer.value = false;
      handelDrawerCancel();
      getSignPageList();
    } catch (err) {
      isLoadingDrawer.value = false;
    }
  });
};

getSignPageList();
</script>

<style scoped lang="scss">
@import "contractingParty";
</style>
